package com.example.treehole.ui.page.square

import androidx.lifecycle.ViewModel
import com.example.treehole.service.DataRepository
import com.example.treehole.ui.model.PostInfo
import com.example.treehole.ui.model.PostType
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update

class SquarePostListViewModel : ViewModel() {
    private val _squarePostList = MutableStateFlow<List<PostInfo>>(emptyList())
    val squarePostList: StateFlow<List<PostInfo>> = _squarePostList
    private val _squarePage = MutableStateFlow(0)
    val squarePage: StateFlow<Int> = _squarePage

    fun updateSquarePostList(posts: List<PostInfo>) {
        _squarePostList.value = posts
    }

    fun addSquarePostList(posts: List<PostInfo>){
        _squarePostList.update { current ->
            current + posts
        }
    }

    suspend fun searchTagPost(
        jwlToken: String,
        searchText: String,
        userId: Int,
        tag: PostType
    ) {
        val res = DataRepository.searchPost(jwlToken, searchText, userId, tag.ordinal)
        res?.let {
            updateSquarePostList(it)
            _squarePage.value = -1 // page表示当前获取的页面编号，search中没有使用因此设置为-1
        }
    }

    suspend fun refreshTagPost(
        jwlToken: String,
        userId: Int,
        tag: PostType
    ){
        val res = DataRepository.askNewPost(jwlToken,userId,tag.ordinal,0)
        res?.let {
            updateSquarePostList(it)
            _squarePage.value = 0
        }
    }

    suspend fun getMoreTagPost(
        jwlToken: String,
        userId: Int,
        tag: PostType
    ){
        val res = DataRepository.askNewPost(jwlToken,userId,tag.ordinal,squarePage.value+1)
//        val res = postList
        res?.let {
            if (it.isNotEmpty()) {
                addSquarePostList(it)
                _squarePage.value++
            } else{
                _squarePage.value = -2
            }
        }
    }
}